use crate::db::dao::im_sensitive_word_dao::{query_sensitive_word_by_word, sensitive_word_inserts, sensitive_word_total, sensitive_word_updates};
use crate::db::db::Db;
use crate::db::db_transaction::transaction;
use crate::db::pojo::pojo::ImSensitiveWord;

pub struct ImSensitiveWordService;

impl ImSensitiveWordService {

    pub fn save_sensitive_words(&self, user_id: String, sensitive_words: &mut Vec<ImSensitiveWord>) {
        let db = Db::open();
        let user_id_clone = user_id.clone();
        transaction(db.clone(), move |db: Db| {
            self.save_sensitive_words_business(db, user_id_clone, sensitive_words)
        });
    }

    pub fn total(&self)->usize {
        let db = Db::open();
        let total = transaction(db.clone(), move |db: Db| {
            sensitive_word_total(db)
        });
        total
    }

    fn save_sensitive_words_business(&self, db: Db, _user_id: String, sensitive_words: &mut Vec<ImSensitiveWord>) {
        let mut insert_sensitive_word_list= Vec::new();
        let mut update_sensitive_word_list = Vec::new();

        for sensitive_word in sensitive_words {
            let db_feedback = query_sensitive_word_by_word(db.clone(), &sensitive_word.word);
            if db_feedback.is_some() {
                sensitive_word.id = db_feedback.unwrap().id.clone();
                update_sensitive_word_list.push(sensitive_word);
            } else {
                insert_sensitive_word_list.push(sensitive_word);
            }
        }

        sensitive_word_inserts(db.clone(), &mut insert_sensitive_word_list);
        sensitive_word_updates(db.clone(), &mut update_sensitive_word_list);
    }

}